package com.example.draw.algorithm;

import com.example.exception.BusinessException;
import com.example.pojo.LotteryPrize;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;

/**
 * 分段抽奖算法
 * <p>
 * 该算法将奖品按概率分段，生成一个随机数，根据随机数所在的段来决定中奖的奖品。
 * 如果抽中库存不足的奖品，则返回默认奖品（谢谢参与）。
 */
@Component
public class SegmentLotteryAlgorithm implements LotteryAlgorithm {
    
    @Override
    public LotteryPrize draw(List<LotteryPrize> prizes) {
        // 按概率分段
        List<Segment> segments = buildSegments(prizes);
        
        // 生成随机数
        double random = Math.random();
        
        for (Segment segment : segments) {
            if (random >= segment.getStart() && random < segment.getEnd()) {
                if (segment.getPrize().getRemainingStock() > 0) {
                    return segment.getPrize();
                }
                break;
            }
        }
        
        return getDefaultPrize(prizes);
    }
    
    private List<Segment> buildSegments(List<LotteryPrize> prizes) {
        List<Segment> segments = new ArrayList<>();
        double current = 0.0;
        
        for (LotteryPrize prize : prizes) {
            double probability = prize.getProbability().doubleValue();
            segments.add(new Segment(current, current + probability, prize));
            current += probability;
        }
        
        return segments;
    }
    private LotteryPrize getDefaultPrize(List<LotteryPrize> prizes) {
        return prizes.stream()
                     .filter(p -> "谢谢参与".equals(p.getName()))
                     .findFirst()
                     .orElseThrow(() -> new BusinessException("未配置默认奖品"));
    }

    @Override
    public String getAlgorithmType() {
        return "segment";
    }
    
    @Data
    @AllArgsConstructor
    private static class Segment {
        private double start;
        private double end;
        private LotteryPrize prize;
    }
    
    // ... getDefaultPrize方法同上
}
